package com.算法.操作系统;
/**
 * @author zh
 * @date 2024-01-03 11:27
 */

class Node {
    PCB data;
    Node next;
    public Node(PCB data) {
        this.data = data;
        this.next = null;
    }
}
public class Queue {
    public Node front;
    public Node rear;
    public int size;

    public Queue() {
        front = null;
        rear = null;
        size = 0;
    }
    // 检查队列是否为空
    public boolean isEmpty() {
        return front == null;
    }
    // 将 PCB 入队列
    public void enqueue(PCB data) {
        Node newNode = new Node(data);
        if (isEmpty()) {
            front = newNode;
        } else {
            rear.next = newNode;
        }
        rear = newNode;
        size++;
    }
    // 从队列中出队列一个 PCB
    public PCB dequeue() {
        if (isEmpty()) {
            System.out.println("出队列dequeue队列为空");
            return null;
        }
        PCB dequeuedItem = front.data;
        front = front.next;
        if (front == null) {
            rear = null;
        }
        size--;
        return dequeuedItem;
    }
    // 获取队列的首个 PCB
    public PCB front() {
        if (isEmpty()) {
            System.out.println("获取队列的首个 PCB  front队列为空");
            return null;
        }
        return front.data;
    }
    // 获取队列的末尾 PCB
    public PCB rear() {
        if (isEmpty()) {
            System.out.println("获取队列的末尾 PCB  rear队列为空");
            return null;
        }
        return rear.data;
    }
    // 获取队列大小
    public int size() {
        return size;
    }
    // 清空队列
    public void clear() {
        front = null;
        rear = null;
        size = 0;
    }
    // 按照剩余时间升序排序队列
    public void sortBySizeDescending() {
        // 空或者等于1，直接返回不需要排序
        if (isEmpty() || size() == 1) {
            return;
        }
        // 从第二个元素开始排序
        Node currentNode = front.next;
        Node nextNode;
        PCB temp;
        while (currentNode != null) {
            nextNode = currentNode.next;
            while (nextNode != null) {
                if (currentNode.data.getRemainingTime() > nextNode.data.getRemainingTime()) {
                    temp = currentNode.data;
                    currentNode.data = nextNode.data;
                    nextNode.data = temp;
                }
                nextNode = nextNode.next;
            }
            currentNode = currentNode.next;
        }
    }
}